package com.ytktt.study.week2.task6;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.concurrent.TimeUnit;

/**
 * OkHttp 请求 demo
 * kotlin实现的库
 *
 * @author ytk
 */
public class OkHttpDemo {

    public static void main(String[] args) throws Exception {
        OkHttpClient client = new OkHttpClient.Builder()
                // 设置连接超时时间（请求服务器发起建立连接的时间）
                .connectTimeout(3, TimeUnit.SECONDS)
                // 设置写入超时时间
                .writeTimeout(3, TimeUnit.SECONDS)
                // 设置读取超时时间
                .readTimeout(3, TimeUnit.SECONDS)
                // 整个网络流程超时时间
                .callTimeout(6, TimeUnit.SECONDS)
                // 连接失败重试
                .retryOnConnectionFailure(true)
                .connectionPool(new ConnectionPool(20, 3, TimeUnit.SECONDS))
                // 添加日志拦截器
                // 核心扩展功能
                .addInterceptor(chain -> {
                    // 这里貌似不能添加header
                    long startTime = System.currentTimeMillis();
                    Request request = chain.request();
                    System.out.println(request.headers());
                    Response response = chain.proceed(request);
                    System.out.println("complete: " + (System.currentTimeMillis() - startTime) + "ms");
                    return response;
                })
                .build();

        Request request = new Request.Builder()
                .url("http://localhost:8081")
                .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }
}
